import { throttle } from 'lodash'
import { ref } from 'vue'

export const useDrag = (style: any) => {
	const Left = ref(style.left)
	const Top = ref(style.top)
	const init = (el: HTMLElement, binding?: any) => {
		// 鼠标在拖拽目标元素内部的位置
		let x = 0
		let y = 0
		let isDragging = false
		const handleMouseDown = (event: MouseEvent) => {
			isDragging = true
			x = event.clientX - el.offsetLeft
			y = event.clientY - el.offsetTop
			document.addEventListener('mousemove', throttle(handleMouseMove, 15))
			document.addEventListener('mouseup', handleMouseUp)
		}
		const handleMouseMove = (event: MouseEvent) => {
			if (isDragging) {
				let newLeft = event.clientX - x
				let newTop = event.clientY - y
				if (newLeft < 0) {
					newLeft = 0
				}
				if (newTop < 0) {
					newTop = 0
				}
				if (newLeft + el.offsetWidth > window.innerWidth) {
					newLeft = window.innerWidth - el.offsetWidth
				}
				if (newTop + el.offsetHeight > window.innerHeight) {
					newTop = window.innerHeight - el.offsetHeight
				}
				Left.value = newLeft
				Top.value = newTop
			}
		}

		const handleMouseUp = () => {
			isDragging = false
			document.removeEventListener('mousemove', handleMouseMove)
			document.removeEventListener('mouseup', handleMouseUp)
		}
		if (binding) {
			let els: HTMLElement[] = el.getElementsByClassName(binding.value) as any
			if (els.length) {
				els[0].addEventListener('mousedown', handleMouseDown)
			}
		} else {
			el.addEventListener('mousedown', handleMouseDown)
		}
	}

	return { Left, Top, init }
}
